package product

import (
	"context"
	"fmt"
	"net/http"
	"wms/model"

	"wms/internal/svc"
	"wms/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type PriceListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewPriceListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PriceListLogic {
	return &PriceListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *PriceListLogic) PriceList(req *types.ProductPriceRequest) (resp *types.ProductPriceResponse, err error) {
	resp = new(types.ProductPriceResponse)

	//1.产品是否存在
	_, err = l.svcCtx.ProductModel.FindOne(l.ctx, req.Id)
	switch err {
	case nil:
	case model.ErrNotFound:
		fmt.Printf("[Error]产品[%d]不存在\n", req.Id)
		resp.Code = http.StatusNoContent
		resp.Msg = "产品不存在"
		return resp, nil
	default:
		fmt.Printf("[Error]查询产品[%d]:%s\n", req.Id, err.Error())
		resp.Code = http.StatusInternalServerError
		resp.Msg = "服务内部错误"
		return resp, nil
	}

	//2.查询产品价格
	prices, err := l.svcCtx.ProductPriceModel.FindByPage(l.ctx, fmt.Sprintf(" where product_id=%d order by id desc", req.Id))
	if err != nil {
		fmt.Printf("[Error]查询产品[%d]价格:%s\n", req.Id, err.Error())
		resp.Code = http.StatusInternalServerError
		resp.Msg = "服务内部错误"
		return resp, nil
	}

	fmt.Println("产品价格：", prices)
	for _, one := range prices {
		resp.Data = append(resp.Data, types.ProductPrice{ProductId: one.ProductId, Price: one.Price, CreatedAt: one.CreatedAt.Unix()})
	}

	resp.Code = http.StatusOK
	resp.Msg = "成功"
	return resp, nil
}
